<template>
  <div class="dedicated_process_doc">
    <secret-upload-dialog
      @uploadComplete="getListData"
      saveInterFace="a/uploadspecialtechprocfilehistory/uploadSpecialTechProcFileHistory/save"
      moduleName="专用工艺文件管理"
      module="dedicatedDoc"
      ref="secretUploadDialog"
    ></secret-upload-dialog>
    <one-title title="专用工艺文件管理" @refreshData="refresh">
      <div class="mes_btn">
        <el-button
          v-btn-permission="'delete'"
          @click="handleDelete">
          <i class="iconfont icon-btn_delete"></i>
          删除
        </el-button>
        <el-button
          v-btn-permission="'relate'"
          @click="handleEdit">
          <i class="iconfont icon-btn_edit"></i>
          数据关联
        </el-button>
        <el-button
          v-btn-permission="'upload'"
          size="small"
          @click="showSecretUpload"
          type="primary">
          <i class="iconfont icon-btn_export"></i>
          上传
        </el-button>
      </div>
    </one-title>
    <div class="fixed_top_56">
      <mes-search-comp
        :searchList="tableColConfig"
        ref="mesSearch"
        :searchResult="searchCount"
        @searchInfo="search"
      ></mes-search-comp>
      <div class="table_container">
        <el-table
          ref="tableNode"
          v-loading="isLoading"
          :max-height="tableMaxHeight"
          :row-class-name="({row}) => $highlightSelectedRow(row, selectItems)"
          :data="listData.list"
          @row-click="(row) => $refs.tableNode.toggleRowSelection(row)"
          @sort-change="handleSortChange"
          @selection-change="handleSelectionChange"
          border
          stripe
          tooltip-effect="dark">
          <el-table-column
            width="40"
            type="selection"
            align="center">
          </el-table-column>
          <mes-col-comp
            v-for="(column,index) in columnList"
            :key="index"
            :column="column">
          </mes-col-comp>
          <el-table-column
            label="操作"
            :resizable="false"
            show-overflow-tooltip
            align="center"
            width="120">
            <template slot-scope="scope">
              <span class="jump_item"
                    @click.stop="$downByBlob(scope.row.uploadHistoryId, scope.row.fileName)">下载</span>
              <span class="jump_item"
                    v-if="$checkPreviewName(scope.row.fileName)&&$checkPreviewSize(scope.row.fileSize)"
                    @click.stop="$previewFile(scope.row.uploadHistoryId)">预览</span>
              <span class="jump_item is_disabled" v-else>预览</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <mes-pagination
        @updateData="getListData"
        :currentPage="listData.pageNo"
        :total="listData.count || 0"
        :pageSize="listData.pageSize">
      </mes-pagination>
    </div>
    <el-dialog
      title="数据关联"
      :visible.sync="dialogVisible"
      v-dialogDrag
      :close-on-click-modal="false"
      customClass="mes_dialog">
      <div class="table_container">
        <el-table
          :data="selectItemsDialog"
          ref="tableDialogNode"
          border
          class="table_dialog">
          <el-table-column
            :class-name="'static_col'"
            prop="fileName"
            label="上传文件名"
            :resizable="false"
            show-overflow-tooltip
            align="left">
            <template slot-scope="scope">
              <file-icon :fileName="scope.row.fileName"></file-icon>
              <span>{{scope.row.fileName}}</span>
            </template>
          </el-table-column>
          <el-table-column
            :class-name="'static_col'"
            prop="uploadDate"
            label="上传时间"
            :resizable="false"
            width="180"
            show-overflow-tooltip
            align="center">
          </el-table-column>
          <el-table-column
            :class-name="'static_col'"
            prop="uploadUser"
            label="上传用户"
            :resizable="false"
            width="160"
            show-overflow-tooltip
            align="center">
          </el-table-column>
          <el-table-column
            prop="productName"
            label="产品名称"
            :resizable="false"
            width="300"
            align="select">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.productBatchId"
                filterable
                :filter-method="filterProduct"
                @focus="resetProductList"
                style="width: 100%"
                placeholder="请选择产品">
                <el-option
                  v-for="item in productList"
                  :key="item.ID"
                  :label="item.NAME+'/'+item.SNUMBER"
                  :value="item.ID">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            prop="workcenterName"
            label="工作中心"
            :resizable="false"
            show-overflow-tooltip
            width="200"
            style="width: 100%"
            align="select">
            <template slot-scope="scope">
              <el-cascader
                :options="workGroupList"
                v-model="scope.row.selectedWorkGroupIDs"
                class="table_cascader"
                placeholder="请选择工作中心">
              </el-cascader>
            </template>
          </el-table-column>
          <!--<el-table-column-->
            <!--label="操作"-->
            <!--:resizable="false"-->
            <!--show-overflow-tooltip-->
            <!--align="center"-->
            <!--fixed="right"-->
            <!--width="120">-->
            <!--<template slot-scope="scope">-->
             <!--<span class="jump_item"-->
                   <!--@click.stop="$downByBlob(scope.row.uploadHistoryId, scope.row.fileName)">下载</span>-->
              <!--<span class="jump_item"-->
                    <!--v-if="$checkPreviewName(scope.row.fileName)&&$checkPreviewSize(scope.row.fileSize)"-->
                    <!--@click.stop="$previewFile(scope.row.uploadHistoryId)">预览</span>-->
              <!--<span class="jump_item is_disabled" v-else>预览</span>-->
            <!--</template>-->
          <!--</el-table-column>-->
        </el-table>
      </div>
      <span slot="footer" class="mes_btn">
        <el-button type="primary" @click="saveRelative">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import FileIcon from '@/components/FileIcon'
import tableColumn from './tableColumn'

// 查询列表接口
let listInterFace = 'a/uploadspecialtechprocfilehistory/uploadSpecialTechProcFileHistory/list'
// 查询产品列表接口
let productInterFace = 'a/product/product/listfields/id,name,snumber'
// 保存关联接口
let saveBatchInterFace = 'a/uploadspecialtechprocfilehistory/uploadSpecialTechProcFileHistory/saveBatch'
// 删除列表项接口
let deleteBatchInterFace = 'a/uploadspecialtechprocfilehistory/uploadSpecialTechProcFileHistory/deleteBatch'

export default {
  name: 'DedicatedProcessDoc',
  components: {
    FileIcon
  },
  data() {
    return {
      tableColConfig: tableColumn, // 列配置
      isLoading: true, // 数据加载中
      searchParams: {}, // 查询参数
      sortOrder: {workcenterName: 'desc'}, // 排序对象
      searchCount: NaN, // 搜索结果数
      selectItemsDialog: [], // 选中弹框中的数据,
      selectItems: [], // 选中的数据,
      dialogVisible: false,
      productList: [] // 可选的产品
    }
  },
  mounted() {
    this.init()
  },
  computed: {
    // 列表数据
    listData() {
      let listData = this.$store.state.dedicatedProcessDoc.listData
      if (listData.list !== undefined) {
        listData.list.map(value => {
          value.selectedWorkGroupIDs = []
          if (value.workgroupId) {
            value.selectedWorkGroupIDs[0] = value.workgroupId
          }
          if (value.workcenterId) {
            value.selectedWorkGroupIDs[1] = value.workcenterId
          }
        })
        return listData
      } else {
        return listData
      }
    },
    workGroupList() {
      let tempStr = JSON.stringify(this.$store.state.dedicatedProcessDoc.workGroupList)
        .replace(/id/g, 'value').replace(/name/g, 'label').replace(/workcenter/g, 'children')
      return JSON.parse(tempStr)
    },
    // 列循环
    columnList() {
      return this.tableColConfig.filter(item => item.noForCol !== true && item.isShow !== false)
    },
  },
  methods: {
    showSecretUpload() {
      this.$refs.secretUploadDialog.openDialog()
    },
    // 初始化方法
    init() {
      this.isLoading = true
      Promise.all([this.getListData(), this.getWorkGroupList(), this.getProductList()])
        .finally(() => {
          this.isLoading = false
        })
    },
    getListData(page) {
      this.isLoading = true
      let pageObj = page || {
        pageNo: 1,
        pageSize: this.listData.pageSize || 15
      }
      let postData = {
        method: 'post',
        url: listInterFace,
        module: 'dedicatedProcessDoc',
        data: {
          pageNo: pageObj.pageNo,
          pageSize: pageObj.pageSize,
          query: this.searchParams,
          sort: this.sortOrder
        },
        state: 'listData',
      }
      return this.$store.dispatch('saveData', postData).then(res => {
        if (Object.keys(this.searchParams).length > 0) {
          this.searchCount = res.count
        } else {
          this.searchCount = NaN
        }
      }).finally(() => {
        this.selectItemsDialog = []
        this.isLoading = false
      })
    },
    // 请求工作中心树
    getWorkGroupList() {
      let commitObj = {
        method: 'get',
        url: 'a/workgroup/workgroup/nametree',
        module: 'dedicatedProcessDoc',
        state: 'workGroupList'
      }
      return this.$store.dispatch('saveData', commitObj)
    },
    // 请求产品列表
    getProductList() {
      let commitObj = {
        method: 'get',
        url: productInterFace,
        module: 'dedicatedProcessDoc',
        state: 'productList'
      }
      return this.$store.dispatch('saveData', commitObj).then(() => {
        this.$store.state.dedicatedProcessDoc.productList.map(value => {
          value.index = (value.SNUMBER + value.NAME).toLowerCase()
        })
        this.productList = this.$store.state.dedicatedProcessDoc.productList
      })
    },
    // 下拉框搜索产品，按产品名称和产品型号模糊查找
    filterProduct(value) {
      this.productList = this.$store.state.dedicatedProcessDoc.productList.filter(item => item.index.includes(value.trim().toLowerCase()))
    },
    // 点击打卡下拉框时，重置可选的产品列表
    resetProductList() {
      this.productList = this.$store.state.dedicatedProcessDoc.productList
    },
    // 搜索方法
    search(params) {
      this.searchParams = params
      this.getListData()
    },
    // 排序方法
    handleSortChange(e) {
      this.sortOrder = this.$getSortOrder(e)
      this.getListData()
    },
    // 刷新方法
    refresh() {
      this.searchParams = {} // 查询参数
      this.sortOrder = {workcenterName: 'desc'} // 排序对象
      this.$refs.mesSearch.clean()
      this.$refs.tableNode.clearSort()
      this.init()
    },
    // 选中方法
    handleSelectionChange(val) {
      this.selectItems = val
    },
    // 编辑方法
    handleEdit() {
      if (this.selectItems.length) {
        // 每次编辑时重置选择的数据
        this.selectItemsDialog = JSON.parse(JSON.stringify(this.selectItems))
        this.dialogVisible = true
      } else {
        this.$message.error({
          message: '未选择任何数据',
          duration: 1500,
          center: true
        })
      }
    },
    // 保存关联
    saveRelative() {
      let commitObj = {
        method: 'post',
        url: saveBatchInterFace,
        data: {uploadSpecialTechProcFileHistoryList: this.getEditedData()},
        noCommit: true
      }
      this.$store.dispatch('saveData', commitObj).then(() => {
        this.dialogVisible = false
        this.getListData()
      })
    },
    // 构造已编辑的关联
    getEditedData() {
      let arr = []
      this.selectItemsDialog.map(value => {
        if (value.selectedWorkGroupIDs) {
          arr.push({
            id: value.id,
            workgroupId: value.selectedWorkGroupIDs[0],
            workcenterId: value.selectedWorkGroupIDs[1],
            productBatchId: value.productBatchId
          })
        }
      })
      return arr
    },
    // 删除提示信息
    handleDelete() {
      if (this.selectItems.length) {
        this.confirmDelete().then(() => {
          this.deleteItems()
        }).catch(() => {
        })
      } else {
        this.$message.error({
          message: '未选择任何数据',
          duration: 1500,
          center: true
        })
      }
    },
    // 删除
    deleteItems() {
      let postData = {
        method: 'post',
        url: deleteBatchInterFace,
        module: 'dedicatedProcessDoc',
        data: {
          uploadSpecialTechProcFileHistoryList: this.selectItems
        },
        noCommit: true
      }
      this.$store.dispatch('saveData', postData).then(() => {
        this.$message.success({
          message: '删除成功',
          duration: 1500,
          center: true
        })
        this.getListData(this.listData)
      })
    }
  }
}
</script>

<style lang="less">
  .dedicated_process_doc .mes_dialog{
    width: 1200px;
  }
</style>
<style lang="less" scoped>
  .dedicated_process_doc {
    .file_name {
      color: #3c8dbc;

      &:hover {
        cursor: pointer;
      }
    }

    .table_cascader {
      width: 100%;
    }

    .operation {
      color: #00b4ff;
      display: flex;
      justify-content: space-around;

      .iconfont {
        cursor: pointer;

        &.disicon {
          cursor: not-allowed;
          color: #a1b1c1;
        }
      }
    }
  }
</style>
